package demo0912;

import java.util.PriorityQueue;

class TimerTask implements Comparable<TimerTask> {
    private Runnable runnable;
    private long time;

    public TimerTask(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = time;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(TimerTask o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer {
    private PriorityQueue<TimerTask> priorityQueue = new PriorityQueue<>();
    private Object locker = new Object();
    public void schedule (Runnable runnable, long delay) {
        synchronized (locker) {
            priorityQueue.offer(new TimerTask(runnable,delay + System.currentTimeMillis()));
            locker.notify();
        }
    }

    public MyTimer() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                while (true) {
                    synchronized (locker) {
                        while (priorityQueue.isEmpty()) {
                            try {
                                locker.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        TimerTask task = priorityQueue.peek();
                        if (task.getTime() <= System.currentTimeMillis()) {
                            task.getRunnable().run();
                            priorityQueue.poll();
                        } else {
                            try {
                                locker.wait(task.getTime() - System.currentTimeMillis());
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            }
        };
        thread.start();
    }
}


public class T1_0523 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(()->{
            System.out.println(3000);
        },3000);
        timer.schedule(()->{
            System.out.println(2000);
        },2000);
        timer.schedule(()->{
            System.out.println(1000);
        },1000);
    }
}
